<template>
    <div class="lx_login">
        <!-- 导航栏 -->
        <div class="lx_nav">
            <div class="lx_nav_left"><van-icon name="arrow-left" size="23" onclick="history.back()" /></div>
            <div class="lx_nav_right">登录</div>
        </div>
        <!-- 文字 -->
        <div class="lx_text">
            <div class="lx_text_title">欢迎回来</div>
            <div style="text-align: center; color:#b0b0ba">使用您的用户名和密码登录或继续使用社交媒体</div>
        </div>
        <!-- 表单 -->
        <div class="lx_form">
            <div class="lx_phone">
                <div style="margin-top: 5px">
                    <van-cell-group inset>
                        <van-field v-model="username" center clearable label="用户名" placeholder="请输入用户名"
                            :class="{ 'focused': isFocused }" @focus="handleFocus" @blur="handleBlur"></van-field>
                    </van-cell-group>
                </div>
            </div>

            <div class="lx_sms">

                <div style="margin-top: 8px;margin-left:15px">
                    <van-field v-model="password" type="password" label="密码" :class="{ 'focused': isSmsFocused }"
                        @focus="handleSmsFocus" @blur="handleSmsBlur" placeholder="请输入密码" />
                </div>

            </div>

            <!-- 记住账号 -->
            <div class="lx_remember">
                <div class="lx_remeber_pwd"><input type="checkbox">记住密码</div>
                <div class="lx_regist_pwd"></div>
            </div>
        </div>
        <!-- 登录按钮 -->
        <div class="lx_login_btn" @click="forgotten">
            <p>登录</p>
        </div>

        <!-- 跳转其他登录页面icon -->
        <div class="lx_other_login">
            <div class="lx_other"><van-icon name="manager-o" size="30" color="#00be8c" style="margin-left: 15px;"
                    @click="toUserLogin" /></div>
            <div class="lx_other"><van-icon name="apps-o" size="30" color="#00be8c" style="margin-left: 15px;" @click="redirectToGitee"/></div>
            <div class="lx_other"><van-icon name="free-postage" size="30" color="#00be8c" style="margin-left: 15px;"
                    @click="toEmailLogin" /></div>
                    <div class="lx_other"><van-icon name="phone-o" size="30" color="#00be8c" style="margin-left: 15px;" @click="toPhoneLogin"/></div>
        </div>

        <!-- 没有账户？立即注册 -->
        <div class="lx_register" @click="toRegister">
               <p>没有账户？立即注册</p>
            </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue';
import { Icon as VanIcon, CellGroup as VanCellGroup, Field as VanField, Button as VanButton } from 'vant';
import axios from 'axios'
import router from '@/router';
import { showSuccessToast, showFailToast } from 'vant';
import { log } from 'console';

// 定义表单数据
const username = ref('');
const password = ref('')

// icon跳转
const toEmailLogin = () => {
    router.push('/emaillogin')
}

const toPhoneLogin=()=>{
    router.push('/login')
}

const toRegister=()=>{
    router.push('/register')
}

const toUserLogin = () => {
    router.push('/userlogin')
}

// 控制文本颜色的响应式变量
const isFocused = ref(false);
// 控制文本颜色的响应式变量
const isPhoneFocused = ref(false);
const isSmsFocused = ref(false);
// 处理聚焦事件
const handleFocus = () => {
    isFocused.value = true;
};

// 处理失焦事件
const handleBlur = () => {
    isFocused.value = false;
};

// 处理短信验证码输入框的聚焦事件
const handleSmsFocus = () => {
    isSmsFocused.value = true;
};

// 处理短信验证码输入框的失焦事件
const handleSmsBlur = () => {
    isSmsFocused.value = false;
};


// 正则表达式
const regex = /^[a-zA-Z0-9]+([_-]?[a-zA-Z0-9]+)*$/
const forgotten = async () => {
    if (regex.test(username.value)) {
        
        try {
            console.log('username:', username.value);

            const res = await axios.post('http://127.0.0.1:3000/lx/Towlogin', { username: username.value, password: password.value });
            console.log(res.data.code);
            if (res.data.code === 200) {
                showSuccessToast('登录成功');
                router.push('/home');
                localStorage.setItem('user', JSON.stringify(res.data.data));
                localStorage.setItem('accessToken', res.data.accessToken);
                localStorage.setItem('refreshToken', res.data.refreshToken);
            } else {
                showFailToast('登录失败');
            }
        } catch (error) {
            console.error('Error during login:', error);
            showFailToast('登录失败');
        }
    }
};
axios.interceptors.request.use(
    (config) => {
        const accessToken = localStorage.getItem('accessToken');
        if (accessToken) {
            config.headers.Authorization = `Bearer ${accessToken}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    (response) => response,
    async (error) => {
        const originalRequest = error.config;

        // 如果响应状态码为 401 且不是因为尝试刷新令牌导致的
        if (error.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;
            const refreshToken = localStorage.getItem('refreshToken');

            if (refreshToken) {
                try {
                    const res = await axios.post('http://127.0.0.1:3000/lx/refresh-token', { refreshToken });
                    const newAccessToken = res.data.accessToken;

                    localStorage.setItem('accessToken', newAccessToken);
                    originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;

                    return axios(originalRequest);
                } catch (err) {
                    console.error('Failed to refresh token:', err);
                    localStorage.removeItem('accessToken');
                    localStorage.removeItem('refreshToken');
                    localStorage.removeItem('user');
                    router.push('/login'); // 重定向到登录页面
                }
            }
        }

        return Promise.reject(error);
    }
);


const redirectToGitee = () => {
    const clientId = 'bbe1345c39d503ff57c4755464029e516c98fb833175c555d95a38e7438778ad' // 这是在Gitee上创建的应用层序所获得的客户端ID
    const redirectUri = encodeURIComponent('http://localhost:5173/home') // 用户授权完成之后，Gitee会将用户重定向这个URL
    // const scope = 'user_info' // 请求的权限范围
    // const state = ''

    const authUrl = `https://gitee.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`
    window.location.href = authUrl
    console.log(authUrl)

}

</script>

<style>
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.lx_login {
    width: 100vw;
    height: 100vh;

}

.lx_nav {
    width: 100%;
    height: 50px;
    display: flex;
    border-bottom: 1px solid #ccc;
}

.lx_nav_left {
    width: 50px;
    height: 30px;
    margin-left: 30px;
    margin-top: 14px;
}


.lx_nav_right {
    width: 310Px;
    height: 50px;
    font-size: 18px;
    margin-left: 120px;
    line-height: 50px;
}

.lx_text {
    width: 100%;
    height: 50px;
    margin-top: 50px;
    /* background: pink; */
}


.lx_text_title {
    font-size: 25px;
    text-align: center;
    line-height: 50px;
}

.lx_form {
    width: 100%;
    height: 250px;
    overflow: hidden;
    margin-top: 50px;
    background: #fff;
}

.lx_phone {
    width: 100%;
    height: 55px;
    margin-top: 50px;
    border: 1px solid #ccc;
    border-radius: 50px;
}

.lx_sms {
    width: 100%;
    height: 60px;
    margin-top: 10px;
    border: 1px solid #ccc;
    border-radius: 50px;
}

.lx_phone .van-cell-group,
.lx_sms .van-cell-group {
    background: #f9f9f9;
}

.van-field {
    background: #ffffff;
}

.van-field.focused .van-cell__title,
.van-field.focused .van-cell__value,
.van-field.focused .van-field__control {
    color: #00be8c !important;
}

.van-button {
    background: #00be8c;
    color: white;
}

.van-field.focused .van-cell__title,
.van-field.focused .van-cell__value,
.van-field.focused .van-field__control {
    color: #00be8c !important;
}

.lx_remember {
    width: 100%;
    height: 50px;
    margin-top: 30px;
    display: flex;
    justify-content: space-around;
}

.lx_remeber_pwd {
    width: 100px;
    height: 50px;
    line-height: 50px;
}

.lx_regist_pwd {
    width: 220px;
    height: 50px;
    text-align: right;
    line-height: 50px;
    color: #cecece;
}

.lx_login_btn {
    width: 95%;
    height: 50px;
    background: #00be8c;
    margin-left: 10px;
    margin-top: 20px;
    border-radius: 8px;
}

.lx_login_btn p {
    text-align: center;
    line-height: 50px;
    color: #fff;
}

.lx_other_login {
    width: 100%;
    height: 50px;
    /* background: palegreen; */
    margin-top: 60px;
    display: flex;
    justify-content: space-around;
}

.lx_other {
    width: 60px;
    height: 50px
}

.lx_register {
    width: 100%;
    height: 50px;
    margin-top: 20px;
    text-align: center;
    line-height: 50px;
    color: #989898;
}
</style>